package com.dailyblue.java.spring.boot.mvc.mybatis.service.impl;

import com.dailyblue.java.spring.boot.commons.bean.User;
import com.dailyblue.java.spring.boot.commons.exception.UserCodeNotFoundException;
import com.dailyblue.java.spring.boot.commons.exception.UserPasswordErrorException;
import com.dailyblue.java.spring.boot.commons.util.JsonResult;
import com.dailyblue.java.spring.boot.commons.util.JwtConfig;
import com.dailyblue.java.spring.boot.commons.util.ResultTool;
import com.dailyblue.java.spring.boot.mvc.mybatis.mapper.UserMapper;
import com.dailyblue.java.spring.boot.mvc.mybatis.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public JsonResult logout(String token) {
        log.info("token:{}", token);
        boolean b = JwtConfig.checkToken(token);
        log.info("b:{}", b);
        if (b) {
            String id = JwtConfig.getMemberIdByJwtToken(token);
            log.info("id:{}", id);
            ValueOperations<String, String> value = stringRedisTemplate.opsForValue();
            value.getAndDelete("token:" + id);
        }
        return ResultTool.success();
    }

    @Override
    public JsonResult isLogin(String token) {
        String id = JwtConfig.getMemberIdByJwtToken(token);
        if (!JwtConfig.checkToken(token)) {
            return ResultTool.fail();
        }
        ValueOperations<String, String> value = stringRedisTemplate.opsForValue();
        String token1 = value.get("token:" + id);
        if (!token.equals(token1)) {
            return ResultTool.fail();
        }
        return ResultTool.success(id);
    }

    public JsonResult login(User user) throws UserCodeNotFoundException, UserPasswordErrorException {
        String userCode = user.getUserCode();

        User user1 = userMapper.login(userCode);
        if (user1 == null) {
            throw new UserCodeNotFoundException("");
        }
        String pass1 = user.getPassword();
        pass1 = DigestUtils.md5Hex(pass1);
        String pass2 = user1.getPassword();
        if (!pass2.equals(pass1)) {
            throw new UserPasswordErrorException("");
        }
        JsonResult result = ResultTool.success(user1, user1.getId() + "");
        String token = JwtConfig.getJwtToken(result);
        ValueOperations<String, String> value = stringRedisTemplate.opsForValue();
        value.set("token:" + user1.getId(), token);
        return ResultTool.success(token, user1.getId() + "");
    }
}
